<template>
  <div class="my-orders">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的订单</span>
          <el-radio-group v-model="orderType" @change="loadOrders">
            <el-radio-button label="buyer">我购买的</el-radio-button>
            <el-radio-button label="seller">我售出的</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      
      <!-- 筛选栏 -->
      <div class="filter-bar">
        <el-select v-model="filters.status" placeholder="选择状态" clearable @change="loadOrders" style="width: 200px">
          <el-option label="待付款" value="pending" />
          <el-option label="已付款" value="paid" />
          <el-option label="已发货" value="shipped" />
          <el-option label="已完成" value="completed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
      </div>
      
      <!-- 订单列表 -->
      <div class="order-list" v-loading="loading">
        <el-empty v-if="!loading && orders.length === 0" description="暂无订单" />
        <div
          v-for="order in orders"
          :key="order.id"
          class="order-item"
        >
          <div class="order-header">
            <div class="order-info">
              <span class="order-no">订单号: {{ order.order_no }}</span>
              <span class="order-time">{{ order.created_at }}</span>
            </div>
            <el-tag :type="getStatusType(order.status)">
              {{ getStatusText(order.status) }}
            </el-tag>
          </div>
          
          <div class="order-content">
            <div class="textbook-info">
              <el-image
                :src="getTextbookImage(order.textbook_images)"
                fit="cover"
                style="width: 100px; height: 100px; border-radius: 4px;"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="textbook-details">
                <h4>{{ order.textbook_title }}</h4>
                <p v-if="orderType === 'buyer'">卖家: {{ order.seller_name }}</p>
                <p v-if="orderType === 'seller'">买家: {{ order.buyer_name }}</p>
                <p v-if="orderType === 'seller' && order.remark" class="buyer-message">
                  买家消息: {{ order.remark }}
                </p>
              </div>
            </div>
            
            <div class="order-actions">
              <div class="price">¥{{ order.price }}</div>
              <div class="actions">
                <el-button
                  v-if="order.status === 'pending' && orderType === 'buyer'"
                  type="primary"
                  size="small"
                  @click="updateOrderStatus(order.id, 'paid')"
                >
                  确认付款
                </el-button>
                <el-button
                  v-if="order.status === 'paid' && orderType === 'seller'"
                  type="success"
                  size="small"
                  @click="updateOrderStatus(order.id, 'shipped')"
                >
                  确认发货
                </el-button>
                <el-button
                  v-if="order.status === 'shipped' && orderType === 'buyer'"
                  type="success"
                  size="small"
                  @click="updateOrderStatus(order.id, 'completed')"
                >
                  确认收货
                </el-button>
                <el-button
                  v-if="order.status === 'pending'"
                  type="danger"
                  size="small"
                  @click="cancelOrder(order.id)"
                >
                  取消订单
                </el-button>
                <el-button
                  size="small"
                  @click="viewOrderDetail(order.id)"
                >
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination" v-if="pagination.total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="订单详情"
      width="600px"
    >
      <div v-if="orderDetail" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ orderDetail.order_no }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(orderDetail.status)">
              {{ getStatusText(orderDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="教材名称">{{ orderDetail.textbook_title }}</el-descriptions-item>
          <el-descriptions-item label="价格">¥{{ orderDetail.price }}</el-descriptions-item>
          <el-descriptions-item label="买家">{{ orderDetail.buyer_name }}</el-descriptions-item>
          <el-descriptions-item label="卖家">{{ orderDetail.seller_name }}</el-descriptions-item>
          <el-descriptions-item label="收货人">{{ orderDetail.buyer_name }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ orderDetail.buyer_phone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">{{ orderDetail.buyer_address }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ orderDetail.remark || '无' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ orderDetail.created_at }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ orderDetail.updated_at }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import { orderApi } from '../api/order'
import mathTextbook from '@/assets/images/math_textbook.svg'
import englishTextbook from '@/assets/images/english_textbook.svg'
import computerTextbook from '@/assets/images/computer_textbook.svg'
import physicsTextbook from '@/assets/images/physics_textbook.svg'

const loading = ref(false)
const orders = ref([])
const orderType = ref('buyer')
const showDetailDialog = ref(false)
const orderDetail = ref(null)
const filters = reactive({
  status: ''
})
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 加载订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      status: filters.status
    }
    
    // 根据订单类型设置参数
    const userStr = localStorage.getItem('user')
    if (userStr) {
      try {
        const user = JSON.parse(userStr)
        if (orderType.value === 'buyer') {
          params.buyer_id = user.user_id || user.id // 使用登录用户的ID
        } else {
          params.seller_id = user.user_id || user.id // 使用登录用户的ID
        }
      } catch (e) {
        console.error('解析用户数据失败:', e)
      }
    }
    
    const response = await orderApi.getOrders(params)
    if (response.success) {
      orders.value = response.data
      pagination.total = response.pagination.total
    }
  } catch (error) {
    console.error('加载订单失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取教材图片
const getTextbookImage = (images) => {
  if (images && images.length > 0) {
    return images[0]
  }
  // 返回默认图片
  return mathTextbook // 默认使用数学教材图片
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    'pending': 'warning',
    'paid': 'info',
    'shipped': '',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return types[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '待付款',
    'paid': '已付款',
    'shipped': '已发货',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return texts[status] || '未知'
}

// 更新订单状态
const updateOrderStatus = async (id, status) => {
  try {
    const response = await orderApi.updateOrderStatus(id, status)
    if (response.success) {
      ElMessage.success('操作成功')
      loadOrders()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('更新订单状态失败:', error)
    ElMessage.error('操作失败')
  }
}

// 取消订单
const cancelOrder = async (id) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await orderApi.cancelOrder(id)
    if (response.success) {
      ElMessage.success('订单已取消')
      loadOrders()
    } else {
      ElMessage.error(response.message || '取消订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 查看订单详情
const viewOrderDetail = async (id) => {
  try {
    const response = await orderApi.getOrderById(id)
    if (response.success) {
      orderDetail.value = response.data
      showDetailDialog.value = true
    }
  } catch (error) {
    console.error('加载订单详情失败:', error)
    ElMessage.error('加载订单详情失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.page = 1
  loadOrders()
}

const handleCurrentChange = (val) => {
  pagination.page = val
  loadOrders()
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.my-orders {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.filter-bar {
  margin-bottom: 20px;
}

.order-list {
  margin-bottom: 20px;
}

.order-item {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 15px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.order-no {
  font-weight: bold;
  color: #303133;
}

.order-time {
  font-size: 12px;
  color: #909399;
}

.order-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.textbook-info {
  display: flex;
  gap: 15px;
  flex: 1;
}

.textbook-details h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.textbook-details p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.buyer-message {
  color: #409eff;
  font-weight: bold;
  margin-top: 8px;
  padding: 5px 10px;
  background-color: #ecf5ff;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.order-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
}

.price {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
}

.actions {
  display: flex;
  gap: 10px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  color: #909399;
  font-size: 30px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.order-detail {
  padding: 20px 0;
}
</style>

